#第十七章 使用期物处理并发

#实例1 通过队列加载 不是并发加载

import os,time,sys
import requests

POP20_CC = ('CN IN US ID BR PK NG BD RU JP '
'MX PH VN ET EG DE IR TR CD FR').split()

BASE_URL = "http://flupy.org/data/flags/"

ROOT = os.path.split(__file__)[0]

DEST_DIR = os.path.join(ROOT,'downloads_chp17')

def  save_flag(img,filename):
    path = os.path.join(DEST_DIR,filename)
    with open(path,'wb') as fb:
        fb.write(img) #保存下载的图片

def get_flag(cc): #下载旗图片
    url = '{}/{cc}/{cc}.gif'.format(BASE_URL,cc=cc.lower())
    resp = requests.get(url) #通过requests包获取到内容
    #print("resp.content",resp.content)
    print("",url,' is loaded ')
    return resp.content #二进制的图片数据

def show(text):
    print(text,end='')
    sys.stdout.flush()

def download_many(cc_list):
    for cc in sorted(cc_list):
        img = get_flag(cc)
        save_flag(img,cc.lower()+'.gif')
    return len(cc_list)


def main(download_many):
    t0 = time.time()
    count = download_many(POP20_CC)
    elapsed = time.time() - t0
    msg = '\n{} flags downloaded in {:.2f}s'
    print(msg.format(count, elapsed))

if __name__ == "__main__":
    main(download_many)